package com.xin.demo.sigle;

/**
 * 饿汉模式，按需分配
 */
public class Single03 {

    private static Single03 INSTANCE = null;

    /**
     * 构造器必须私有化，不允许外部进行对象的创建
     */
    private Single03() {
    }

    public static Single03 getINSTANCE() {
        if (INSTANCE == null) {
            // 此处验证多线程并发的问题，虽然此处达到了 按需分配，但是多线程时不安全
            try {
                Thread.sleep(30);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            INSTANCE = new Single03();
        }
        return INSTANCE;
    }

    public static void main(String[] args) {
        System.out.println(2);
        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                System.out.println(Single03.getINSTANCE().hashCode());
            }).start();
        }
    }
}
